#include "inquirepurchasecommodity.h"
#include "ui_inquirepurchasecommodity.h"
#include "inquiresql.h"
#include <QDebug>
#include <QKeyEvent>

InquirePurchaseCommodity::InquirePurchaseCommodity(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::InquirePurchaseCommodity)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);   
    setWindowTitle(tr("选择商品"));

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    m_selectAllLineEditInquireText = false;
//    setWindowFlags( Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool );

    QHeaderView* vheaderView = ui->tableWidgetPurchaseCommodity->verticalHeader();
    vheaderView->setHidden(true);

    //设置列宽可拖动
//    ui->tableWidgetPurchaseCommodity->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
//    ui->tableWidgetPurchaseCommodity->verticalHeader()->setResizeMode(QHeaderView::Interactive);
    //设置table的水平滚动条
    ui->tableWidgetPurchaseCommodity->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    ui->tableWidgetPurchaseCommodity->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    QWidget::installEventFilter(this);
    ui->tableWidgetPurchaseCommodity->installEventFilter(this);
    ui->lineEditInquire->installEventFilter(this);
    ui->pushButtonDisplayAll->installEventFilter(this);
}

InquirePurchaseCommodity::~InquirePurchaseCommodity()
{
    delete ui;
}

void InquirePurchaseCommodity::changelineEditInquire(QString inquireInformation)
{
//    ui->lineEditInquire->setFocus();
    ui->tableWidgetPurchaseCommodity->setFocus();
    if (inquireInformation.isEmpty())
    {
        ui->tableWidgetPurchaseCommodity->clear();
        ui->tableWidgetPurchaseCommodity->setRowCount(0);
//        setTableWidgetHeaderStyle();
    }
    else
        ui->lineEditInquire->setText(inquireInformation);
    setTableWidgetHeaderStyle();
}

bool InquirePurchaseCommodity::eventFilter(QObject *target, QEvent *event)
{
    if( target == this || target == ui->tableWidgetPurchaseCommodity
     || target == ui->lineEditInquire ||target == ui->pushButtonDisplayAll)
    {
        if (event->type() == QEvent::FocusOut)
        {
            if (target == ui->tableWidgetPurchaseCommodity)
            {
                ui->tableWidgetPurchaseCommodity->setStyleSheet("background-color:white");
//                setTableWidgetColor();
                return true;
            }
            if (target == ui->lineEditInquire)
            {
                m_selectAllLineEditInquireText = false;
//                return true;
            }
        }
        if (event->type() == QEvent::FocusIn)
        {
            if (target == ui->tableWidgetPurchaseCommodity)
            {
                ui->tableWidgetPurchaseCommodity->setStyleSheet("\
                    background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, \
                    stop: 0 rgba(255, 0, 0, 30%), stop: 0.2 rgba(255, 128, 0, 30%), \
                    stop: 0.4 rgba(255, 255, 0, 30%), stop: 0.6 rgba(0, 255, 0, 30%), \
                    stop: 0.8 rgba(0, 128, 255, 30%), stop: 1 rgba(128, 0, 255, 30%)); ");
                return true;
            }
        }
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
            {
                if (target == ui->pushButtonDisplayAll)
                {
                    displayPurchaseCommodityInformaton("all");
                    return true;
                }
//                if (ui->tableWidgetPurchaseCommodity->currentRow() >= 0)
                if (ui->tableWidgetPurchaseCommodity->rowCount())
                {
                    on_tableWidgetPurchaseCommodity_cellDoubleClicked(
                            ui->tableWidgetPurchaseCommodity->currentRow(), 0);
                    return true;
                }
//                goto flag;
            }
            if (keyEvent->key() == Qt::Key_F1 || keyEvent->key() == Qt::Key_Tab)
            {
                if (target == ui->tableWidgetPurchaseCommodity)
                {
                    ui->lineEditInquire->setFocus();
                    ui->lineEditInquire->selectAll();
                    return true;
                }
                if (target == ui->lineEditInquire)
                {
                    ui->pushButtonDisplayAll->setFocus();
                    return true;
                }
                if (target == ui->pushButtonDisplayAll)
                {
                    ui->tableWidgetPurchaseCommodity->setFocus();
                    return true;
                }
                else
                {
                    ui->lineEditInquire->setFocus();
                    ui->lineEditInquire->selectAll();
                    return true;
                }
            }
        }
        //鼠标左键按下事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->lineEditInquire)
                {
                    if (!m_selectAllLineEditInquireText){
                        m_selectAllLineEditInquireText = true;
                        ui->lineEditInquire->selectAll();
                        return true;
                    }else if (m_selectAllLineEditInquireText)
                    {
                        goto flag;
                    }
                }
            }
        }
       //窗口停用，变为不活动的窗口
        if(QEvent::WindowDeactivate == event->type())
        {
            this->hide();  //或者关闭窗口,加入自己的操作.
            return true ;
        }
        else
        {
            return false ;
        }
    }
flag:
    return QWidget::eventFilter(target, event);
}

void InquirePurchaseCommodity::keyPressEvent(QKeyEvent *ev)
{
    switch(ev->key())
    {
        case Qt::Key_Escape:
            this->hide();
            break;
    default:
        QWidget::keyPressEvent(ev);
    }
}

void InquirePurchaseCommodity::displayPurchaseCommodityInformaton(const QString &inquireInformation)
{
    m_list.clear();
    m_list = m_sql->InquireCommodityInformation();
    ui->tableWidgetPurchaseCommodity->clear();
//    ui->tableWidgetPurchaseCommodity->setRowCount(m_list.count());

    setTableWidgetHeaderStyle();

    //判断需要显示的商品信息的行数
    int RowCount = 0;
    if (inquireInformation != "all")
    {
//        if (ui->lineEditInquire->text().isEmpty())
//        {

//            return;
//        }
        for(int i = 0; i < m_list.count(); ++i)
        {
            if (!(m_list.at(i).get_commodityBarcode().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_commodityName().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_internalCode().contains(inquireInformation, Qt::CaseInsensitive)))
            {
                continue;
            }
            else
            {
                RowCount++;
            }
        }
        ui->tableWidgetPurchaseCommodity->setRowCount(RowCount);
        RowCount = 0;
    }
    else
    {
        ui->tableWidgetPurchaseCommodity->setRowCount(m_list.count());
    }

    //显示进货商品信息
    RowCount = 0;
    for(int i = 0; i < m_list.count(); ++i)
    {
        if (inquireInformation != "all")
        {
            if (!(m_list.at(i).get_commodityBarcode().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_commodityName().contains(inquireInformation, Qt::CaseInsensitive)
                    || m_list.at(i).get_internalCode().contains(inquireInformation, Qt::CaseInsensitive)))
            {
                continue;
            }
        }

        QString specifications = m_sql->InquireAttributeValue(Specification,
                                                                m_list.at(i).get_specificationsNumber());
        QString category = m_sql->InquireAttributeValue(Category,
                                                                m_list.at(i).get_categoryNumber());
        QString color = m_sql->InquireAttributeValue(Color, m_list.at(i).get_colorNumber());
        QString brand = m_sql->InquireAttributeValue(Brand, m_list.at(i).get_brandNumbe());
        QString unit = m_sql->InquireAttributeValue(Unit, m_list.at(i).get_unitNumber());

        QTableWidgetItem *commodityBarcode      = new QTableWidgetItem(m_list.at(i).get_commodityBarcode());
        QTableWidgetItem *commodityName         = new QTableWidgetItem(m_list.at(i).get_commodityName());
        QTableWidgetItem *internalCode          = new QTableWidgetItem(m_list.at(i).get_internalCode());
        QTableWidgetItem *categoryNumber        = new QTableWidgetItem(category);
        QTableWidgetItem *specificationsNumber  = new QTableWidgetItem(specifications);
        QTableWidgetItem *colorNumber           = new QTableWidgetItem(color);
        QTableWidgetItem *brandNumber           = new QTableWidgetItem(brand);
        QTableWidgetItem *unitNumber            = new QTableWidgetItem(unit);
        QTableWidgetItem *discount              = new QTableWidgetItem(m_list.at(i).get_discount());
        QTableWidgetItem *shelfLife             = new QTableWidgetItem(m_list.at(i).get_shelfLife());
        QTableWidgetItem *sellingPrice          = new QTableWidgetItem(m_list.at(i).get_sellingPrice());
        QTableWidgetItem *memberPrice           = new QTableWidgetItem(m_list.at(i).get_memberPrice());
        QTableWidgetItem *stockQuantity         = new QTableWidgetItem(m_list.at(i).get_stockQuantity());
        QTableWidgetItem *remark                = new QTableWidgetItem(m_list.at(i).get_remark());

        //设置对齐方式
        commodityBarcode->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        internalCode->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        categoryNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        specificationsNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        colorNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        unitNumber->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        discount->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        sellingPrice->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        memberPrice->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        stockQuantity->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        shelfLife->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );

        //设置文字颜色
//        rechargeTimes->setTextColor(QColor(0, 0, 255));
//        saleQuantity->setTextColor(QColor(0, 0, 255));
//        rechargeAmount->setTextColor(QColor(255, 0, 0));
//        totalSales->setTextColor(QColor(255, 0, 0));
//        profit->setTextColor(QColor(255, 0, 255));

        //设置文字字体大小
        commodityBarcode->setFont(QFont("DejaVu Sans", 11, 2, false));
        commodityName->setFont(QFont("DejaVu Sans", 11, 2, false));
        internalCode->setFont(QFont("DejaVu Sans", 11, 2, false));
        categoryNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        specificationsNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        colorNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        unitNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        discount->setFont(QFont("DejaVu Sans", 11, 2, false));
        sellingPrice->setFont(QFont("DejaVu Sans", 11, 2, false));
        memberPrice->setFont(QFont("DejaVu Sans", 11, 2, false));
        stockQuantity->setFont(QFont("DejaVu Sans", 11, 2, false));
        brandNumber->setFont(QFont("DejaVu Sans", 11, 2, false));
        shelfLife->setFont(QFont("DejaVu Sans", 11, 2, false));
        remark->setFont(QFont("DejaVu Sans", 11, 2, false));

        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 0, commodityBarcode);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 1, commodityName);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 2, internalCode);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 3, categoryNumber);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 4, specificationsNumber);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 5, colorNumber);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 6, unitNumber);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 7, discount);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 8, sellingPrice);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 9, memberPrice);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 10, stockQuantity);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 11, brandNumber);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 12, shelfLife);
        ui->tableWidgetPurchaseCommodity->setItem(RowCount, 13, remark);

        RowCount++;
    }

    ui->tableWidgetPurchaseCommodity->setCurrentItem(
                ui->tableWidgetPurchaseCommodity->item(RowCount - 1 , 1));

    //设置与文字相匹配的单元格大小
    ui->tableWidgetPurchaseCommodity->resizeColumnsToContents();
    ui->tableWidgetPurchaseCommodity->resizeRowsToContents();

    setTableWidgetColor();
}

void InquirePurchaseCommodity::setTableWidgetColor()
{
    for (int i = 0; i < ui->tableWidgetPurchaseCommodity->rowCount(); ++i)
    {
        if (i % 2 == 0)
        {
            for (int j = 0; j < ui->tableWidgetPurchaseCommodity->columnCount(); ++j)
            {
                QTableWidgetItem *item = ui->tableWidgetPurchaseCommodity->item(i,j);
                if (item)
                {
                    const QColor color = QColor(252,222,156);
                    item->setBackgroundColor(color);
                }
            }
        }
    }
}

void InquirePurchaseCommodity::setTableWidgetHeaderStyle()
{
    QStringList headers;
    headers << tr("商品编码") << tr("商品名称") << tr("商品内码") << tr("类别") << tr("规格") << tr("颜色")
            << tr("单位") << tr("折扣") << tr("零售价") << tr("会员价") << tr("库存数量")
            << tr("品牌") << tr("保质期") << tr("备注");

    ui->tableWidgetPurchaseCommodity->setColumnCount(14);
    ui->tableWidgetPurchaseCommodity->setHorizontalHeaderLabels(headers);

    for (int i = 0; i < 14; ++i)
    {
        ui->tableWidgetPurchaseCommodity->horizontalHeaderItem(i)->setFont(QFont("Helvetica"));
        ui->tableWidgetPurchaseCommodity->horizontalHeaderItem(i)->setTextColor(QColor(200,111,30));
    }
}

void InquirePurchaseCommodity::on_pushButtonDisplayAll_clicked()
{
    displayPurchaseCommodityInformaton("all");
    ui->tableWidgetPurchaseCommodity->setFocus();
}

void InquirePurchaseCommodity::on_tableWidgetPurchaseCommodity_cellDoubleClicked(int row, int)
{
    emit displayCommodityInformation(ui->tableWidgetPurchaseCommodity->item(row, 0)->text());
//    qDebug() << ui->tableWidgetPurchaseCommodity->item(row, 0)->text();
    this->hide();
}

void InquirePurchaseCommodity::on_pushButtonSelete_clicked()
{
    if (ui->tableWidgetPurchaseCommodity->currentRow() >= 0)
    {
        emit displayCommodityInformation(ui->tableWidgetPurchaseCommodity->item(
                                         ui->tableWidgetPurchaseCommodity->currentRow(), 0)->text());
        this->hide();
    }
    else
    {
        ui->lineEditInquire->setFocus();
    }
}

void InquirePurchaseCommodity::on_lineEditInquire_textChanged(const QString &arg1)
{
    displayPurchaseCommodityInformaton(arg1);
}
